<template>
    <div id="layout" class=" home easyui-layout layout easyui-fluid" data-options="fit:true">

        <div class="top panel layout-panel layout-panel-north">
            <div data-options="region:'north'" style="overflow: hidden; width: 100%; height: 100%;" title=""
                 class="panel-body panel-body-noheader layout-body">
                <!--工具栏-->
                <div style="width:100%;height:100%;line-height:3px;">
                    <table width="100%" height="31" border="0" cellpadding="0" cellspacing="0"
                           background="http://map.jiudingmap.com:8081/MyGISEditor/images/zhengwu-06.gif">
                        <tbody>
                        <tr>
                            <td align="right">
                                <table height="32" border="0" cellpadding="0" cellspacing="0">
                                    <tbody>
                                    <tr>
                                        <td width="100" align="center">
                                            <div class="STYLE2" align="center">
                                                <a href="javascript:void(0)"
                                                   class="easyui-linkbutton l-btn l-btn-small l-btn-plain"
                                                   data-options="plain:true,iconCls: 'icon-usermanager' "
                                                   @click="goLink('/manager')" group="" id="">
                                                    <span class="l-btn-left l-btn-icon-left">
                                                        <span class="l-btn-text">后台管理</span>
                                                        <span class="l-btn-icon icon-usermanager">&nbsp;</span>
                                                    </span>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!--        主页面-->
        <div class="main panel layout-panel layout-panel-center">

            <div data-options="region:'center'" title=""
                 class="panel-body panel-body-noheader layout-body panel-noscroll" style="width: 100%; height: 100%;">

                <div id="maintabs" class="easyui-tabs tabs-container easyui-fluid"
                     data-options="fit:true,border:false,plain:true" style="width: 100%; height: 100%;">
                    <!--                    上-->
                    <div class="tabs-header tabs-header-plain tabs-header-noborder" style="width: 100%;height: 5%">
                        <div class="tabs-scroller-left" style="display: none;"></div>
                        <div class="tabs-scroller-right" style="display: none;"></div>
                        <div class="tabs-wrap" style="margin-left: 0px; margin-right: 0px; width: 100%;">
                            <ul class="tabs" style="height: 26px;">
                                <li class="tabs-selected tabs-first tabs-last"><a href="javascript:void(0)"
                                                                                  class="tabs-inner"
                                                                                  style="height: 25.4px; line-height: 25.4px;"><span
                                    class="tabs-title"></span><span class="tabs-icon"></span></a></li>
                            </ul>
                        </div>
                    </div>
                    <!--                    下-->
                    <div class="tabs-panels tabs-panels-noborder" style=" width: 100%;height: 95%">
                        <div class="panel" style="display: block; width: 100%;height: 100%">
                            <div class="panel-noscroll panel-body panel-body-noheader panel-body-noborder" title=""
                                 style="width: 100%; height: 100%;">
                                <div class="easyui-layout layout easyui-fluid" fit="true"
                                     style="width: 100%; height: 100%;">
                                    <!--                            下上-->
                                    <div class="panel layout-panel layout-panel-north"
                                         style="width: 100%; left: 0px; top: 0px;height: 5%;">
                                        <div region="north" border="false"
                                             style="overflow-y: hidden; position: relative; margin-left: 5px; width: 100%; height: 29px;"
                                             title=""
                                             class="panel-body panel-body-noheader panel-body-noborder layout-body">
                                            <!--
                                            开始日期：<input id="startdate" class="easyui-datebox" >
                                            结束日期：<input id="enddate" class="easyui-datebox" >
                                            <a id="btn" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search',onClick:function(){livePlay();}">查询</a>
                                            -->
                                            <form id="locationFormdd" style="margin-top: 1px">

                                                北纬:<input style="height: 25px; width: 125px; display: none;"
                                                            class="easyui-textbox textbox-f" id="lat" data-options=""
                                                            textboxname="lat">
                                                <span class="textbox" style="width: 123.4px; height: 23.4px;">
                                                        <input type="text" v-model="lat"
                                                               class="textbox-text validatebox-text textbox-prompt"
                                                               autocomplete="off" placeholder=""
                                                               style="margin-left: 0px; margin-right: 0px; padding-top: 0px; padding-bottom: 2px; width: 115.4px;">
                                                        <input type="hidden" class="textbox-value" name="lat">
                                                    </span>
                                                东经:<input style="height: 25px; width: 125px; display: none;"
                                                            class="easyui-textbox textbox-f" id="lon" data-options=""
                                                            textboxname="lon"><span class="textbox"
                                                                                    style="width: 123.4px; height: 23.4px;"><input
                                                type="text" v-model="lon"
                                                class="textbox-text validatebox-text textbox-prompt"
                                                autocomplete="off" placeholder=""
                                                style="margin-left: 0px; margin-right: 0px; padding-top: 0px; padding-bottom: 2px; width: 115.4px;"><input
                                                type="hidden" class="textbox-value" name="lon"></span>

                                                <a href="javascript:void(0)" class="easyui-linkbutton l-btn l-btn-small"
                                                   style="background:#F68D3C;color:white;padding-bottom:1px;"
                                                   @click="locationReset()" group="" id=""><span
                                                    class="l-btn-left"><span
                                                    class="l-btn-text">重置</span></span></a>
                                                <a href="javascript:void(0)" class="easyui-linkbutton l-btn l-btn-small"
                                                   style="background:#F68D3C;color:white;padding-bottom:1px;"
                                                   @click="locationPoint()" group="" id=""><span
                                                    class="l-btn-left"><span
                                                    class="l-btn-text">定位</span></span></a>
                                                <a href="javascript:void(0)" class="easyui-linkbutton l-btn l-btn-small"
                                                   style="background:#F68D3C;color:white;padding-bottom:1px;"
                                                   @click="save()" group="" id=""><span class="l-btn-left"><span
                                                    class="l-btn-text">保存</span></span></a>
                                            </form>
                                        </div>
                                    </div>
                                    <!--                            下下（map）-->
                                    <div class="panel layout-panel layout-panel-center"
                                         style="width: 100%; left: 0px; top: 29px;height: 80%">
                                        <div region="center" border="false"
                                             style="padding: 0px; overflow: hidden; width: 100%; height: 100%;" title=""
                                             class="panel-body panel-body-noheader panel-body-noborder layout-body">

                                            <div id="map" title="地图" data-options=""
                                                 style="position:relative;width:100%;height:100%;">
                                                <!--                                                todo-->
                                                <!-- 第一部分-->
                                                <div class="mygislog">个人开发</div>
                                                <!-- 第二部分（openlayer自带dom：ol-viewport）-->

                                                <!-- 第三部分-->
                                                <div id="mouse-position"
                                                     style="right: 150px; bottom: 5px; position: absolute;z-index: 1000;">
                                                    <div class="custom-mouse-position" v-if="shape != ''">
                                                        &nbsp;{{ shape }}
                                                    </div>
                                                </div>
                                                <!--                                                map-->
                                            </div>

                                        </div>

                                    </div>
                                    <!--/不显示 （开始日期，结束那里）-->
                                    <div class="panel layout-panel layout-panel-south layout-split-south"
                                         style="width: 100%; left: 0px;height: 15%">
                                        <div style="background-color: grey;width: 100%;height: 33%"></div>

                                        <div region="south" split="true" data-options="
                                                  region:'west',
                                                  split:true,
                                                  onExpand:function(){
                                                    //alert('onExpand');
                                                    updateMapSizeSys('onExpand');
                                                    //alert('onExpand');
                                                    } ,
                                                  onCollapse:function(){
                                                    //alert('onCollapse');
                                                    updateMapSizeSys('onCollapse');
                                                    //alert('onCollapse');
                                                    }
                                                    ,onResize:function(){
                                                    //alert('onResize');
                                                    updateMapSizeSys('onStopResize');
                                                    }
                                                    " style="border-style: none; width: 100%; height: 67%;" title=""
                                             class="panel-body panel-body-noheader layout-body">

                                            <div style="margin-top:10px;height: 100%;">
                                                &nbsp;&nbsp;开始日期：<input
                                                style="width: 180px; height: 25px; display: none;" id="startdate"
                                                class="easyui-datetimebox combo-f textbox-f datetimebox-f">
                                                <span class="spanclass textbox combo datebox"
                                                      style="width: 178.4px; height: 26.4px;">
                                                                            <input v-model="start" type="date"
                                                                                   class="textbox combo datebox"
                                                                                   style="width: 100%;height: 100%;background-color: rgb(204, 232, 207)">
                                                                        </span>
                                                &nbsp;&nbsp;结束日期：<input
                                                style="width: 180px; height: 25px; display: none;" id="enddate"
                                                class="easyui-datetimebox combo-f textbox-f datetimebox-f">
                                                <span class="spanclass textbox combo datebox"
                                                      style="width: 178.4px; height: 26.4px;">
                                                                            <input v-model="end" type="date"
                                                                                   class="textbox combo datebox"
                                                                                   style="width: 100%;height: 100%;background-color: rgb(204, 232, 207)">
                                                                        </span>

                                                &nbsp;&nbsp;
                                                <a @click="query" id="btn" href="#"
                                                   class="easyui-linkbutton l-btn l-btn-small"
                                                   style="padding-left: 0px; background: rgb(246, 141, 60); color: white; width: 78.4px; text-align: center; position: static; display: inline-block; left: auto;"
                                                   data-options="iconCls:'icon-search',onClick:function(){findWeather();}"
                                                   group="">
                                                                            <span class="l-btn-left l-btn-icon-left"
                                                                                  style="margin-top: 0px;">
                                                                                <span class="l-btn-text">查询</span>
                                                                                <span class="l-btn-icon icon-search">&nbsp;</span>
                                                                            </span>
                                                </a>
                                                <span class="l-btn-text"
                                                      style="margin-left: 10px;color: rgb(57,176,70)">数据显示在下方</span>

                                            </div>

                                            <div v-if="querydata.length !=0">
                                                <div>所有数据如下且已定位到地图黄色标记处</div>
                                                <div v-for="(item,ind) in querydata" :key="ind">
                                                    北纬：<span>{{ item[1] }}</span>
                                                    东经：<span>{{ item[0] }}</span>
                                                </div>
                                            </div>
                                            <div v-else>请输入日期</div>

                                        </div>

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>


            </div>
        </div>


    </div>
</template>

<script>
import Map from 'ol/Map';
import XYZ from 'ol/source/XYZ';
import TileLayer from 'ol/layer/Tile';
import View from 'ol/View';
import 'ol/ol.css';
import {queryApi, queryNameBylonlatApi, saveApi} from "@/api";
import {layxMessage} from "@/utils/layxUtil";
import {Feature} from "ol";
import {Point} from "ol/geom";
import {Fill, Stroke, Style} from "ol/style";
import CircleStyle from "ol/style/Circle";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
// eslint-disable-next-line no-unused-vars
import {extend as extendExtent} from 'ol/extent';
// import { format as formatExtent } from 'ol/coordinate';
import {FullScreen, ScaleLine, Zoom} from "ol/control";

export default {
    name: "Map",
    components: {},
    watch: {
        lon(newValue, oldValue) {
            console.log(`lon${oldValue}变成了${newValue}`);
        },
        // querydata(newValue, oldValue) {
        //     console.log(`querydata${oldValue}变成了${newValue}`);
        //     this.init(this)
        // }
        shape(newValue, oldValue) {
            console.log(`shape${oldValue}变成了${newValue}`);
        },
    },
    data() {
        return {
            map: '',
            lon: '',//东经
            lat: '',//北纬
            shape: '',//北纬
            start: '',//开始时间
            end: '',//结束时间
            querydata: []
        }
    },
    methods: {
        init(that) {
            let source = new XYZ({
                url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
            })
            const AMapLayer = new TileLayer({
                source: source
            });

            // 创建比例尺控件
            const scaleLineControl = new ScaleLine({
                className: 'ol-scale-line',
                units: 'metric', // 或者 'imperial' 对于英制单位
                target: 'map', // 默认会添加到地图的 DOM 元素中
            });

            // 创建全屏控件
            const fullScreenControl = new FullScreen({
                source: 'map' // 指定触发全屏的元素，默认为导航栏控件
            });
            //   创建缩放控件
            const zoomControl = new Zoom();
            // 初始化地图
            that.map = new Map({
                layers: [AMapLayer],
                target: 'map',
                view: new View({
                    projection: "EPSG:4326",
                    center: [115.7, 39.4],
                    zoom: 8,
                }),
                controls: [scaleLineControl, fullScreenControl, zoomControl]
            });
            // 绑定点击事件
            // .bind(this)可以确保在事件处理函数中this指向Vue实例，从而正确地访问this.lon和this.lat属性。
            // 当然你也可以在调用init的时候把vue的this传进去即可
            // 为什么map中的this不是vue中的this呢因为使用某些库（如OpenLayers）时，this的上下文可能会不同。这通常发生在库的作者没有使用Vue的$mount方法或者类似的机制来集成库时。
            that.map.on('click', function (evt) {
                console.log('点击事件', evt)
                console.log(evt.coordinate)
                this.lon = Number(evt.coordinate[0].toFixed(6))
                this.lat = Number(evt.coordinate[1].toFixed(6))
                console.log('map', this)
                console.log(that.lon)
                console.log(that.lat)
                this.shape = this.lon + ',' + this.lat
            }.bind(this))
            that.map.on('pointermove', function (evt) {
                console.log('悬浮事件', evt)
                console.log(evt.coordinate)
                let lon = Number(evt.coordinate[0].toFixed(6))
                let lat = Number(evt.coordinate[1].toFixed(6))
                this.shape = lon + ',' + lat
                console.log('shape', this.shape)
            }.bind(this))
        },
        showRedMarkers(coordinates) {
            // 清除之前可能存在的标记（如果有的话）
            let vectorLayer = this.map.getLayers().getArray().find(layer => layer instanceof VectorLayer);
            if (vectorLayer && vectorLayer.getSource() instanceof VectorSource) {
                vectorLayer.getSource().clear();
            }
            // 如果没有找到VectorLayer，则创建一个新的
            if (!vectorLayer) {
                const vectorSource = new VectorSource({
                    features: [] // 初始化时没有特性
                });

                // 创建一个新的VectorLayer来使用新的VectorSource
                vectorLayer = new VectorLayer({
                    source: vectorSource
                });

                // 将VectorLayer添加到地图上
                this.map.addLayer(vectorLayer);
            }
            // 创建并添加点要素
            const features = coordinates.map(coord => {
                const point = new Point(coord);
                const feature = new Feature(point);
                // 设置样式（如果需要）
                feature.setStyle(new Style({
                    image: new CircleStyle({
                        radius: 5,
                        fill: new Fill({
                            color: 'yellow'
                        }),
                        stroke: new Stroke({
                            color: 'black',
                            width: 1
                        })
                    })
                }));
                return feature;
            });
            // 将点要素添加到源中
            const vectorSource = vectorLayer.getSource();
            vectorSource.addFeatures(features);
            // 计算包含所有点的边界
            let extent = features.length > 0 ? features[0].getGeometry().getExtent() : null;
            for (let i = 1; i < features.length; i++) {
                // eslint-disable-next-line no-undef
                extent = extendExtent(extent, features[i].getGeometry().getExtent());
            }
            // 如果extent为空，则不设置新的视图
            // 如果存在扩展范围，添加缓冲
            if (extent) {
                // 假设你想在 x 和 y 轴上各添加 10% 的缓冲
                const bufferRatio = 0.02; // 10% 的缓冲
                const buffer = [
                    extent[0] - extent[0] * bufferRatio, // 减小 x 最小值
                    extent[1] - extent[1] * bufferRatio, // 减小 y 最小值
                    extent[2] + extent[2] * bufferRatio, // 增加 x 最大值
                    extent[3] + extent[3] * bufferRatio  // 增加 y 最大值
                ];

                // 使用新的带缓冲的范围来设置地图的视图
                this.map.getView().fit(buffer, {size: this.map.getSize()}); // 假设 this.map.getSize() 返回地图容器的大小
            }
        },
        query() {
            console.log('start', this.start, Object.prototype.toString.call(this.start))
            console.log('end', this.end, Object.prototype.toString.call(this.end))
            if (this.start == '' || this.end == '') {
                layxMessage.warning('开始日期和结束日期是必填')
            } else if (this.compareDateStrings(this.start, this.end)) {
                //     开始日期低于或等于结束日期
                //     发生请求
                let param = {
                    start: this.start,
                    end: this.end,
                }
                queryApi(param).then(res => {
                    console.log('queryApi', res.data);
                    if (res.data.length == 0) {
                        layxMessage.info('暂时无此日期范围内数据');
                    } else {
                        let strs = res.data;
                        let result = [];
                        strs.forEach(str => {
                            let parts = str.split(",");
                            let lon = parseFloat(parts[0]); // 经度
                            let lat = parseFloat(parts[1]); // 纬度
                            result.push([lon, lat]);
                        });
                        this.querydata = result;
                        console.log('this.querydata', this.querydata);
                        this.showRedMarkers(this.querydata);
                        // 调用方法显示这些点并定位
                        // this.showRedMarkers(this.querydata);
                    }
                }).catch(err => {
                    layxMessage.error(err.msg);
                })
            } else {
                layxMessage.warning('结束日期不低于开始日期，请修改')
            }

        },
        compareDateStrings(dateString1, dateString2) {
            // 创建日期对象
            let date1 = new Date(dateString1);
            let date2 = new Date(dateString2);

            // 检查日期字符串是否有效转换为日期对象
            if (isNaN(date1.getTime()) || isNaN(date2.getTime())) {
                throw new Error('Invalid date string');
            }

            // 比较日期
            if (date1 <= date2) {
                return true;
            } else {
                return false;
            }
        },
        locationReset() {
            this.lon = ''
            this.lat = ''
        },
        locationPoint() {
            if (this.lon != null && this.lat != null && this.lon != '' && this.lat != '') {
                //            定位方法
                const coordinate = [this.lon, this.lat]
                this.zoomToCoordinate(coordinate)
            } else {
                if ((this.lon == null || this.lon == '' || isNaN(this.lon)) && (this.lat == null || this.lat == '' || isNaN(this.lat))) {
                    layxMessage.error('经纬度均没有值,请填写数字')
                } else if (this.lon == null || this.lon == '' || isNaN(this.lon)) {
                    layxMessage.error('经度没有值,请填写数字')
                } else {
                    layxMessage.error('纬度没有值,请填写数字')
                }
            }

        },
        zoomToCoordinate(coordinate) {
            this.map.getView().setCenter(coordinate);
            // 也可以设置缩放级别，如果需要的话
            // map.getView().setZoom(desiredZoomLevel);
        },
        save() {
            // eslint-disable-next-line no-empty
            if (this.lon != null && this.lat != null && this.lon != '' && this.lat != '') {

                queryNameBylonlatApi({
                    // lat=31.14581&lng=121.67892
                    lng: this.lon,
                    lat: this.lat
                }).then(res => {
                    if (res.code == '200') {
                        let data = {
                            shape: this.lon + ',' + this.lat,
                            name: res.data.address
                        }
                        saveApi(data).then(res => {
                            console.log('add', res)
                            layxMessage.success('保存成功')
                        }).catch(err => {
                            console.log('add', err)
                            layxMessage.error('保存失败')
                        })

                    }

                }).then(err => {
                    layxMessage.error(err.message)
                })

            } else {
                if ((this.lon == null || this.lon == '' || isNaN(this.lon)) && (this.lat == null || this.lat == '' || isNaN(this.lat))) {
                    layxMessage.error('经纬度均没有值,请填写数字')
                } else if (this.lon == null || this.lon == '' || isNaN(this.lon)) {
                    layxMessage.error('经度没有值,请填写数字')
                } else {
                    layxMessage.error('纬度没有值,请填写数字')
                }
            }
        },
        //  跳转到指定页页
        goLink(path, params) {
            // 由于props只适用于组件间数据传递，而调用该方法的是一个标签，而不是组件，所以必须使用路由来传参
            this.$router.push({
                path: path,
                query: params
            })

        }
    },
    mounted() {
        this.init(this);
        var element = document.querySelector('.ol-full-screen-false');
        if (element) {
            element.title = '全屏切换'
        }
        var zoomIn = document.querySelector('.ol-zoom-in');
        if (zoomIn) {
            zoomIn.title = '放大'
        }
        var zoomOut = document.querySelector('.ol-zoom-out');
        if (zoomOut) {
            zoomOut.title = '缩小'
        }
    }

}
</script>

<style scoped>
.icon-usermanager {
    background: url('http://map.jiudingmap.com:8081/MyGISEditor/easyui/icons/usermanager.png') no-repeat center center;
}

.home {
    width: 100%;
    height: 97vh;
    margin-top: -7px
}

.top {
    width: 100%;
    left: 0px;
    top: 0px;
    height: 5%;
}

.main {
    width: 100%;
    left: 0px;
    top: 32px;
    height: 95%
}

.textbox .textbox-text {
    font-size: 16px;
    border: 0;
    margin: 0;
    padding: 4px;
    white-space: normal;
    vertical-align: top;
    outline-style: none;
    resize: none;
    -moz-border-radius: 5px 5px 5px 5px;
    -webkit-border-radius: 5px 5px 5px 5px;
    border-radius: 5px 5px 5px 5px;
    color: black;
}

.l-btn {
    margin-left: 10px;
}

.textbox-icon {
    display: inline-block;
    width: 18px;
    height: 20px;
    overflow: hidden;
    vertical-align: top;
    background-position: center center;
    cursor: pointer;
    opacity: 0.6;
    filter: alpha(opacity=60);
    text-decoration: none;
    outline-style: none;
}

.combo-arrow {
    width: 18px;
    height: 20px;
    overflow: hidden;
    display: inline-block;
    vertical-align: top;
    cursor: pointer;
    opacity: 0.6;
    filter: alpha(opacity=60);
}

.spanclass input:focus {
    outline: none; /* 移除默认的焦点轮廓 */
    border: 1px solid rgb(204, 232, 207);
}

.mygislog {
    z-index: 1000;
    position: absolute;
    bottom: 0px;
    right: 10px;
    width: 75px;
    height: 25px;
    cursor: pointer;
}

.custom-mouse-position {

}
</style>
